package cn.bone.mqtt.demo01;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * Created by MD-01 on 2017/4/19.
 */
public class Client {

    public static final String host = "tcp://iot.eclipse.org:1883";
    public static final String topic = "toclient/124";
    private static final String clientid = "client124";
    private MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "admin";

    private void start(){
        try {
            client = new MqttClient(host,clientid,new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setWill("clientWill","client close".getBytes(),2,true);
            client.setCallback(new PushCallback());
            client.connect(options);

            //订阅消息
            int[] Qos  = {1};
            //String[] topic1 = {topic,"serverWill"};

            client.subscribe(topic, 2);
            client.subscribe("serverWill",2);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        Client client = new Client();
        client.start();
    }
}
